package com.bruce.tool.orm.mybatis.generator.plugin;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.util.List;

/**
 * 添加swagger注解到domain
 * 功能 :
 * 1.增加domain类对应字段的字段备注
 *
 * @author : Bruce(刘正航) 20:05 2019-05-11
 */
public class DomainJavaDocPlugin extends PluginAdapter {

    @Override
    public boolean validate(final List<String> list) {
        return true;
    }

    /**
     * 生成实体
     **/
    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        if (StringUtils.isBlank(introspectedTable.getRemarks())) {
            return true;
        }
        addJavaDocLine(topLevelClass, escape(introspectedTable.getRemarks()));
        return true;
    }

    /**
     * 生成字段
     **/
    @Override
    public boolean modelFieldGenerated(final Field field, final TopLevelClass topLevelClass, final IntrospectedColumn introspectedColumn, final IntrospectedTable introspectedTable, final ModelClassType modelClassType) {
        if (StringUtils.isBlank(introspectedColumn.getRemarks())) {
            return true;
        }
        addJavaDocLine(field, escape(StringUtils.replace(introspectedColumn.getRemarks(), "\n", "")));
        return true;
    }

    /**
     * 双引号转换
     **/
    private String escape(String source) {
        return source.replaceAll("\"", "\\\\\"");
    }

    /**
     * 添加表注释
     **/
    private void addJavaDocLine(final TopLevelClass topLevelClass, final String remarks) {
        topLevelClass.getJavaDocLines().clear();
        if (StringUtils.isNotBlank(remarks)) {
            topLevelClass.addJavaDocLine("/**" + remarks + "**/");
        }
    }

    /**
     * 添加行注释
     **/
    private void addJavaDocLine(final Field field, final String remarks) {
        field.getJavaDocLines().clear();
        if (StringUtils.isNotBlank(remarks)) {
            field.addJavaDocLine("/**" + remarks + "**/");
        }
    }
}
